package com.hsbc.dev.teamo4.sms.common.utils.data;

import java.lang.reflect.Field;
import java.util.Comparator;

/**
 * @author : Cady
 * @version:
 * @Project: permission_manage
 * @Package: com.hsbc.dev.teamo4.sms.sm.util
 * @Description:
 * @Date date: 2018-07-26
 */
public class CompareUtil<T> implements Comparator<T> {
    /**
     * 用以排序的属性名
     */
    private String compareField;
    /**
     * 0为升序，1为降序
     */
    private int order;

    public String getCompareField() {
        return compareField;
    }

    public CompareUtil(String compareField, int order) {
        this.compareField = compareField;
        this.order = order;
    }

    public void setCompareField(String compareField) {
        this.compareField = compareField;
    }

    public int getOrder() {
        return order;
    }

    public void setOrder(int order) {
        this.order = order;
    }


    /**
     * @Description: 通过反射将对象通过compareVar按order排序，适用于int，double，String属性排序
     * @Date :13:16 2018-07-19
     * @param a
     * @param b
     * @return int
     */
    @Override
    public int compare(T a,T b){
        try {
            Field field=a.getClass().getDeclaredField(compareField);
            field.setAccessible(true);
            if ("int".equals(field.getGenericType().getTypeName()) ||field.getGenericType().getTypeName().equals("java.lang.Integer")) {
                if (order == 0) {
                    return (Integer) field.get(a) - (Integer) field.get(b);
                } else {
                    return (Integer) field.get(b) - (Integer) field.get(a);
                }
            }
            else if ("double".equals(field.getGenericType().getTypeName())) {
                if (order == 0) {
                    return (int) (field.getDouble(a) - field.getDouble(b));
                } else {
                    return (int) (field.getDouble(b) - field.getDouble(a));
                }
            }
            else if("java.lang.String".equals(field.getGenericType().getTypeName())){
                if(order == 0) {
                    return ((String) field.get(a)).compareTo((String) field.get(b));
                } else {
                    return ((String) field.get(b)).compareTo((String) field.get(a));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
